<template>
  <div class="register-container">
    <div class="register-wrapper">
      <div class="register-card">
        <div class="register-header">
          <h2 class="register-title">
            <i class="bi bi-person-plus-fill me-2"></i>
            用户注册
          </h2>
          <p class="register-subtitle">创建您的 NestJS 学习账户</p>
        </div>

        <!-- 错误和成功消息 -->
        <div v-if="errorMessage" class="alert alert-danger mb-3" role="alert">
          <i class="bi bi-exclamation-triangle-fill me-2"></i>
          {{ errorMessage }}
        </div>

        <div v-if="successMessage" class="alert alert-success mb-3" role="alert">
          <i class="bi bi-check-circle-fill me-2"></i>
          {{ successMessage }}
        </div>

        <form @submit.prevent="handleRegister" class="register-form">
          <div class="mb-3">
            <label for="username" class="form-label">
              <i class="bi bi-person-fill me-1"></i>
              用户名
            </label>
            <input
              id="username"
              v-model="registerForm.username"
              type="text"
              class="form-control"
              :class="{ 'is-invalid': errors.username }"
              placeholder="请输入用户名（2-20个字符）"
              required
            />
            <div v-if="errors.username" class="invalid-feedback">
              {{ errors.username }}
            </div>
          </div>

          <div class="mb-3">
            <label for="email" class="form-label">
              <i class="bi bi-envelope-fill me-1"></i>
              邮箱
            </label>
            <input
              id="email"
              v-model="registerForm.email"
              type="email"
              class="form-control"
              :class="{ 'is-invalid': errors.email }"
              placeholder="请输入邮箱地址"
              required
            />
            <div v-if="errors.email" class="invalid-feedback">
              {{ errors.email }}
            </div>
          </div>

          <div class="mb-3">
            <label for="password" class="form-label">
              <i class="bi bi-lock-fill me-1"></i>
              密码
            </label>
            <div class="password-input-wrapper">
              <input
                id="password"
                v-model="registerForm.password"
                :type="showPassword ? 'text' : 'password'"
                class="form-control"
                :class="{ 'is-invalid': errors.password }"
                placeholder="请输入密码（6-64个字符）"
                required
              />
              <button
                type="button"
                class="password-toggle-btn"
                @click="togglePassword"
                :title="showPassword ? '隐藏密码' : '显示密码'"
              >
                <i :class="showPassword ? 'bi bi-eye-slash-fill' : 'bi bi-eye-fill'"></i>
              </button>
            </div>
            <div v-if="errors.password" class="invalid-feedback">
              {{ errors.password }}
            </div>
          </div>

          <div class="mb-3">
            <label for="confirmPassword" class="form-label">
              <i class="bi bi-lock-check-fill me-1"></i>
              确认密码
            </label>
            <div class="password-input-wrapper">
              <input
                id="confirmPassword"
                v-model="registerForm.confirmPassword"
                :type="showConfirmPassword ? 'text' : 'password'"
                class="form-control"
                :class="{ 'is-invalid': errors.confirmPassword }"
                placeholder="请再次输入密码"
                required
              />
              <button
                type="button"
                class="password-toggle-btn"
                @click="toggleConfirmPassword"
                :title="showConfirmPassword ? '隐藏密码' : '显示密码'"
              >
                <i :class="showConfirmPassword ? 'bi bi-eye-slash-fill' : 'bi bi-eye-fill'"></i>
              </button>
            </div>
            <div v-if="errors.confirmPassword" class="invalid-feedback">
              {{ errors.confirmPassword }}
            </div>
          </div>

          <button type="submit" class="btn btn-primary btn-register" :disabled="isLoading">
            <span v-if="isLoading" class="spinner-border spinner-border-sm me-2"></span>
            <i v-else class="bi bi-person-plus me-2"></i>
            {{ isLoading ? "注册中..." : "注册" }}
          </button>

          <div class="register-links">
            <span>已有账户？</span>
            <a @click.prevent="goToLogin" class="login-link" style="cursor: pointer">立即登录</a>
          </div>
        </form>
      </div>

      <div class="register-footer">
        <p>&copy; 2025 NestJS Learning Project. Built with Vue 3 + Bootstrap 5</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useAuthStore } from "@/stores/auth";
import type { RegisterForm, RegisterErrors } from "@/types/auth";

defineOptions({
  name: "RegisterView",
});

const router = useRouter();
const authStore = useAuthStore();

// 响应式数据
const isLoading = ref(false);
const showPassword = ref(false);
const showConfirmPassword = ref(false);
const errorMessage = ref("");
const successMessage = ref("");

const registerForm = reactive<RegisterForm>({
  username: "",
  email: "",
  password: "",
  confirmPassword: "",
});

const errors = reactive<RegisterErrors>({
  username: "",
  email: "",
  password: "",
  confirmPassword: "",
});

// 初始化
onMounted(() => {
  // 如果已经登录，直接跳转到首页
  if (authStore.isAuthenticated) {
    router.push("/");
  }
});

// 方法
const togglePassword = () => {
  showPassword.value = !showPassword.value;
};

const toggleConfirmPassword = () => {
  showConfirmPassword.value = !showConfirmPassword.value;
};

const validateForm = (): boolean => {
  // 清空之前的错误
  errors.username = "";
  errors.email = "";
  errors.password = "";
  errors.confirmPassword = "";

  let isValid = true;

  // 验证用户名
  if (!registerForm.username.trim()) {
    errors.username = "请输入用户名";
    isValid = false;
  } else if (registerForm.username.length < 2 || registerForm.username.length > 20) {
    errors.username = "用户名长度必须在2-20个字符之间";
    isValid = false;
  }

  // 验证邮箱
  if (!registerForm.email.trim()) {
    errors.email = "请输入邮箱";
    isValid = false;
  } else if (registerForm.email.length < 6 || registerForm.email.length > 32) {
    errors.email = "邮箱长度必须在6-32个字符之间";
    isValid = false;
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.email)) {
    errors.email = "请输入有效的邮箱地址";
    isValid = false;
  }

  // 验证密码
  if (!registerForm.password) {
    errors.password = "请输入密码";
    isValid = false;
  } else if (registerForm.password.length < 6 || registerForm.password.length > 64) {
    errors.password = "密码长度必须在6-64个字符之间";
    isValid = false;
  }

  // 验证确认密码
  if (!registerForm.confirmPassword) {
    errors.confirmPassword = "请确认密码";
    isValid = false;
  } else if (registerForm.password !== registerForm.confirmPassword) {
    errors.confirmPassword = "两次输入的密码不一致";
    isValid = false;
  }

  return isValid;
};

const handleRegister = async () => {
  // 清空之前的消息
  errorMessage.value = "";
  successMessage.value = "";

  if (!validateForm()) {
    return;
  }

  isLoading.value = true;

  try {
    const result = await authStore.signup({
      username: registerForm.username,
      email: registerForm.email,
      password: registerForm.password,
    });

    if (result.success) {
      successMessage.value = result.message + "，即将跳转到登录页面...";

      // 注册成功后跳转到登录页面
      setTimeout(() => {
        router.push("/login");
      }, 2000);
    } else {
      errorMessage.value = result.message;
    }
  } catch (error: any) {
    console.error("注册失败:", error);
    errorMessage.value = error.message || "注册失败，请稍后重试";
  } finally {
    isLoading.value = false;
  }
};

// 跳转到登录页面
const goToLogin = () => {
  router.push("/login");
};
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem 1rem;
}

.register-wrapper {
  width: 100%;
  max-width: 450px;
}

.register-card {
  background: white;
  border-radius: 1rem;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 2.5rem;
  margin-bottom: 2rem;
}

.register-header {
  text-align: center;
  margin-bottom: 2rem;
}

.register-title {
  color: #333;
  font-weight: 700;
  margin-bottom: 0.5rem;
  font-size: 1.75rem;
}

.register-subtitle {
  color: #666;
  margin-bottom: 0;
  font-size: 0.95rem;
}

.register-form .form-label {
  font-weight: 600;
  color: #333;
  margin-bottom: 0.5rem;
}

.form-control {
  border-radius: 0.5rem;
  border: 2px solid #e9ecef;
  padding: 0.75rem 1rem;
  font-size: 1rem;
  transition: all 0.3s ease;
}

.form-control:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
}

.password-input-wrapper {
  position: relative;
}

.password-toggle-btn {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  padding: 0;
  font-size: 1.1rem;
  transition: color 0.2s ease;
}

.password-toggle-btn:hover {
  color: #333;
}

.btn-register {
  width: 100%;
  padding: 0.75rem;
  font-size: 1.1rem;
  font-weight: 600;
  border-radius: 0.5rem;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
  margin-bottom: 1.5rem;
}

.btn-register:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.btn-register:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.register-links {
  text-align: center;
  font-size: 0.9rem;
  color: #666;
}

.login-link {
  color: #667eea;
  text-decoration: none;
  margin-left: 0.5rem;
  cursor: pointer;
  position: relative;
  transition: all 0.3s ease;
}

.login-link::after {
  content: "";
  position: absolute;
  width: 0;
  height: 2px;
  bottom: -2px;
  left: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  transition: all 0.3s ease;
  transform: translateX(-50%);
}

.login-link:hover {
  color: #764ba2;
  text-decoration: none;
  transform: translateY(-1px);
}

.login-link:hover::after {
  width: 100%;
}

.register-footer {
  text-align: center;
  color: rgba(255, 255, 255, 0.8);
  font-size: 0.85rem;
}

.register-footer p {
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .register-container {
    padding: 1rem 0.5rem;
  }

  .register-card {
    padding: 2rem 1.5rem;
  }

  .register-title {
    font-size: 1.5rem;
  }
}

/* 动画效果 */
.register-card {
  animation: slideUp 0.6s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.spinner-border-sm {
  width: 1rem;
  height: 1rem;
}

/* 警告框样式 */
.alert {
  border-radius: 0.5rem;
  border: none;
  font-size: 0.9rem;
}

.alert-danger {
  background-color: #f8d7da;
  color: #721c24;
}

.alert-success {
  background-color: #d1edff;
  color: #0c5460;
}
</style>
